﻿using System;
using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using Firestarter.DB.Schema.BO;

namespace Firestarter.DB.Schema.Logic
{
    public class DBMergeDBPrimaryKeyColumn : DBMergeBO<DBPrimaryKeyColumn>
    {

        protected override void CopyRelationships(DBPrimaryKeyColumn fromPKColumn, DBPrimaryKeyColumn toPKColumn)
        {
            //We only have to deal with the case of merging a DBPrimaryKeys Column relationship.
            // The merging of this relationship is not standard since we need to find the 
            // column from the toTable and and linke this PrimaryKeyColumn to it.
            if (fromPKColumn == null) return;

            if (fromPKColumn.Column == null) return;
            var foundColumn = FindToColumn(fromPKColumn, toPKColumn);
            toPKColumn.Column = foundColumn ?? CreateColumn(toPKColumn.PrimaryKeyDB, fromPKColumn);
        }

        private DBColumn CreateColumn(DBPrimaryKey toPrimaryKey, DBPrimaryKeyColumn fromPKColumn)
        {
            if (toPrimaryKey == null || toPrimaryKey.Table == null) return null;
            var columnMerger = MergeableBORegistry.Instance.Resolve<DBColumn>();
            var column = columnMerger.MergeBOFrom(fromPKColumn.Column, null);
            toPrimaryKey.Table.Columns.Add(column);
           // column.Table = toPrimaryKey.Table;
/*            var column = toPrimaryKey.Table.Columns.CreateBusinessObject();
            column.ColumnName = columnName;
            column.PendingChangeType = ChangeType.Add;*/
            return column;
        }
        private DBColumn FindToColumn(DBPrimaryKeyColumn fromBO, DBPrimaryKeyColumn toBO)
        {
            return toBO.PrimaryKeyDB.Table.Columns.Find(column => column.ColumnName == fromBO.ColumnName);
        }

        public override Func<DBPrimaryKeyColumn, bool> MatchBusinessObject(DBPrimaryKeyColumn boToFind)
        {
            return foundBO => boToFind != null && foundBO != null && foundBO.ColumnName == boToFind.ColumnName;
        }
    }
}